﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace KunURP.Editor
{
    public class KunMainDrawer : MaterialPropertyDrawer
    {
        public string Group { get; private set; }
        public bool DefaultOpen { get; private set; }
        public bool HaveToggle { get; private set; }
        public bool IsOpen { get; private set; }

        public KunMainDrawer() : this("", "", "") {}
        public KunMainDrawer(string group) : this(group, "", "") {}
        public KunMainDrawer(string group, string open) : this(group, open, "") {}
        public KunMainDrawer(string group, string open, string haveToggle)
        {
            this.Group = group;
            this.DefaultOpen = open == "true";
            this.HaveToggle = haveToggle == "true";
            this.IsOpen = this.DefaultOpen;
        }

        public override void OnGUI(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor)
        {
            // Setup
            bool value = (prop.floatValue != 0.0f);

            EditorGUI.BeginChangeCheck();
            EditorGUI.showMixedValue = prop.hasMixedValue;

            var style = new GUIStyle("ShurikenModuleTitle");
            style.font = EditorStyles.boldLabel.font;
            style.fontSize = EditorStyles.boldLabel.fontSize;
            style.fontStyle = EditorStyles.boldLabel.fontStyle;
            style.border = new RectOffset(15, 7, 4, 4);
            style.fixedHeight = 30;
            style.contentOffset = new Vector2(this.HaveToggle ? 50f : 26f, -2f);

            var rect = GUILayoutUtility.GetRect(16f, 30f, style);
            GUI.Box(rect, this.Group, style);

            var e = Event.current;

            var foldOutRect = new Rect(rect.x + 4f, rect.y + 8f, 13f, 13f);

            var toggleRect = new Rect(foldOutRect.x + 20f, foldOutRect.y, 13f, 13f);

            if (e.type == EventType.Repaint)
            {
                EditorStyles.foldout.Draw(foldOutRect, false, false, this.IsOpen, false);
            }

            if (this.HaveToggle)
            {
                value = EditorGUI.Toggle(toggleRect, "", value);
            }

            if (e.type == EventType.MouseDown && foldOutRect.Contains(e.mousePosition))
            {
                this.IsOpen = !this.IsOpen;
                e.Use();
            }

            EditorGUI.showMixedValue = false;
            
            if (EditorGUI.EndChangeCheck())
            {
                // Set the new value if it has changed
                prop.floatValue = value ? 1.0f : 0.0f;
                ShaderDrawUtility.RefreshMaterialsKeywordEnabled(
                    editor.targets,
                    ShaderDrawUtility.GetShaderKeyword(prop.name),
                    value
                );
            }

            ShaderDrawUtility.RefreshGroupIsOpen(this.Group, this.IsOpen);
        }
    }
}
